﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace XmWpfBase.Models
{
    internal class MainWindowModel : INotifyPropertyChanged
    {
        private ObservableCollection<MailAccount> _accounts;
        private ObservableCollection<MailAccount> _filteredAccounts = new ObservableCollection<MailAccount>();
        private string _searchKeyword = "";
        private MailAccount _currentAccount;
        private static readonly string ConfigPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config", "config.json");

        public MainWindowModel()
        {
            Accounts = new ObservableCollection<MailAccount>();
            Load();
            FilterAccounts(""); // 初始化时显示全部
            Accounts.CollectionChanged += (s, e) => FilterAccounts(_searchKeyword); // 保证增删账号时同步过滤
        }

        public ObservableCollection<MailAccount> Accounts
        {
            get => _accounts;
            set
            {
                if (_accounts != value)
                {
                    _accounts = value;
                    OnPropertyChanged();
                }
            }
        }

        public ObservableCollection<MailAccount> FilteredAccounts
        {
            get => _filteredAccounts;
            set
            {
                if (_filteredAccounts != value)
                {
                    _filteredAccounts = value;
                    OnPropertyChanged();
                }
            }
        }

        public MailAccount CurrentAccount
        {
            get => _currentAccount;
            set
            {
                if (_currentAccount != value)
                {
                    _currentAccount = value;
                    OnPropertyChanged();
                }
            }
        }

        public void FilterAccounts(string keyword)
        {
            _searchKeyword = keyword ?? "";
            FilteredAccounts.Clear();
            foreach (var acc in Accounts)
            {
                if (string.IsNullOrEmpty(_searchKeyword) || acc.Account.Contains(_searchKeyword, StringComparison.OrdinalIgnoreCase))
                    FilteredAccounts.Add(acc);
            }
        }

        public void Save()
        {
            try
            {
                var directory = Path.GetDirectoryName(ConfigPath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                var options = new JsonSerializerOptions
                {
                    WriteIndented = true
                };

                var json = JsonSerializer.Serialize(Accounts.ToList(), options);
                File.WriteAllText(ConfigPath, json);
            }
            catch (Exception ex)
            {
                // 这里可以添加日志记录
                System.Diagnostics.Debug.WriteLine($"保存配置失败: {ex.Message}");
            }
        }

        public void Load()
        {
            try
            {
                if (File.Exists(ConfigPath))
                {
                    var json = File.ReadAllText(ConfigPath);
                    var accounts = JsonSerializer.Deserialize<List<MailAccount>>(json);
                    Accounts.Clear();
                    foreach (var account in accounts)
                    {
                        Accounts.Add(account);
                    }
                }
            }
            catch (Exception ex)
            {
                // 这里可以添加日志记录
                System.Diagnostics.Debug.WriteLine($"加载配置失败: {ex.Message}");
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
